import labelRecordService, {
  type PageListReq,
} from "@/api/services/tool/labelRecordService";
import CustomTable from "@/components/grid/CustomTable";
import TableDictTag from "@/components/grid/TableDictTag";
import useDictionary from "@/hooks/system/useDictionary";
import { t } from "@/locales/i18n";
import { Button, Card, Form, Input, Space } from "antd";
import type { ColumnsType } from "antd/es/table";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import type { ToolLabelRecord } from "./entity";

export default function ToolLabelRecordPage() {
  const [loading, setLoading] = useState(false);
  const [queryParams, setQueryParams] = useState<PageListReq>({
    materialId: undefined,
    labelCode: undefined,
    printTime: undefined,
    page: 1,
    pageSize: 10,
  });
  const [total, setTotal] = useState(0);
  const [list, setList] = useState<ToolLabelRecord[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  //动态设置表格高度
  const [tableScrollY, setTableScrollY] = useState(0);
  const PAGE_OFFSET_HEIGHT = 405;
  const updateTableHeight = () => {
    const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
    setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
  };

  useEffect(() => {
    updateTableHeight(); // 初始化
    window.addEventListener("resize", updateTableHeight);
    return () => window.removeEventListener("resize", updateTableHeight);
  }, []);

  const columns: ColumnsType<ToolLabelRecord> = [
    {
      title: "物料编码",
      width: 120,
      key: "materialCode",
      dataIndex: "materialCode",
    },
    {
      title: "物料名称",
      width: 120,
      key: "materialName",
      dataIndex: "materialName",
    },
    {
      title: "标签条码",
      width: 200,
      key: "labelCode",
      dataIndex: "labelCode",
    },
    {
      title: "最小包装数量",
      width: 120,
      key: "qty",
      dataIndex: "qty",
    },
    {
      title: "标签状态",
      width: 120,
      key: "status",
      dataIndex: "status",
      render: (_, record) => (
        <TableDictTag dictCode="system_status" value={record.status ?? ""} />
      ),
    },
    {
      title: "打印时间",
      width: 120,
      key: "printTime",
      dataIndex: "printTime",
    },
    {
      title: "打印人",
      width: 120,
      key: "printUserName",
      dataIndex: "printUserName",
    },
    {
      title: "补打时间",
      width: 120,
      key: "reprintTime",
      dataIndex: "reprintTime",
    },
    {
      title: "补打人",
      width: 120,
      key: "reprintUser",
      dataIndex: "reprintUserName",
    },
  ];

  //加载表格数据
  const fetchPageList = () => {
    setLoading(true);
    labelRecordService
      .pageList(queryParams)
      .then((res) => {
        setList(res.records);
        setTotal(res.total);
      })
      .catch((error) => {
        console.log(error);
        toast.error("获取数据失败！", error);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
  useEffect(() => {
    fetchPageList();
  }, [queryParams]);

  //选择其他页
  const handlePageChange = (newPage: number, newPageSize: number) => {
    setQueryParams((prev) => ({
      ...prev,
      page: newPage,
      pageSize: newPageSize,
    }));
  };

  return (
    <>
      <Card className="mb-4">
        <Form
          layout="inline"
          onFinish={(values) => {
            setQueryParams((prev) => ({
              ...prev,
              ...values,
              page: 1,
            }));
          }}
        >
          <Form.Item name="materialId" label="产品ID">
            <Input placeholder="请输入产品ID" allowClear />
          </Form.Item>
          <Form.Item name="labelCode" label="标签条码">
            <Input placeholder="请输入标签条码" allowClear />
          </Form.Item>
          <Form.Item
            name="printTime"
            label="打印时间"
            getValueFromEvent={(value) => {
              return value ? value.format("YYYY-MM-DD") : null;
            }}
            getValueProps={(value) => ({
              value: value ? dayjs(value, "YYYY-MM-DD") : undefined,
            })}
          >
            <Input placeholder="请输入打印时间" allowClear />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button
              className="ml-2"
              onClick={() => {
                setQueryParams({ page: 1, pageSize: 10 });
              }}
            >
              重置
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <div className="h-4" />
      <Card>
        <CustomTable
          loading={loading}
          columnsConfig={columns}
          dataSource={list}
          total={total}
          selectedRowKeys={selectedRowKeys}
          setSelectedRowKeys={setSelectedRowKeys}
          current={queryParams.page}
          pageSize={queryParams.pageSize}
          onRefresh={fetchPageList}
          onPageChange={handlePageChange}
          selectable
          scroll={{ y: tableScrollY }}
        />
      </Card>
    </>
  );
}
